<template>
  <div>
    <div class="content">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="名称：" prop="name">
          <el-input v-model="ruleForm.name" placeholder="限30个字" />
        </el-form-item>
        <el-form-item label="货号：" prop="item_no">
          <el-input v-model="ruleForm.item_no" class="el-200" :disabled="itemNo_disable" />
          <span class="ml-10">如果您不输入商品货号，系统将自动生成一个唯一的货号</span>
        </el-form-item>
        <div v-if="classificationList" class="classify">
          <el-form-item label="一级分类：">
            <el-select v-model="value1" placeholder="请选择" @change="handleChange">
              <el-option
                v-for="item of classificationList"
                :key="item.id"
                :label="item.kind_name"
                :value="item.id"
                :disabled="noDisable"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="二级分类：" prop="kind">
            <el-select
              v-model="value2"
              placeholder="请选择"
              :disabled="disabled"
              @change="handleSecClassicChange"
            >
              <el-option
                v-for="item of secClassicList"
                :key="item.id"
                :label="item.kind_name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </div>
        <!-- <el-form-item label="品牌选择：">
          <el-select v-model="value3" placeholder="请选择" @change="handleBrandChange">
            <el-option
              v-for="item in brandList"
              :key="item.id"
              :label="item.brand_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item> -->
        <div class="price-wrapper">
          <el-form-item label="成本价：" prop="cost">
            <el-input v-model="ruleForm.cost" class="el-127" />
            <span class="yuan">元</span>
          </el-form-item>
          <el-form-item label="原价：" prop="original_price">
            <el-input v-model="ruleForm.original_price" class="el-127" />
            <span class="yuan">元</span>
          </el-form-item>
          <el-form-item label="现价：" prop="price">
            <el-input v-model="ruleForm.price" class="el-127" />
            <span class="yuan">元</span>
          </el-form-item>
          <!-- <el-form-item label="会员价：" prop="discount_price">
            <el-input v-model="ruleForm.discount_price" class="el-127" />
            <span class="yuan">元</span>
          </el-form-item> -->
        </div>
        <div class="stock">
          <el-form-item label="库存：" prop="inventory">
            <el-input v-model="ruleForm.inventory" class="el-127" :disabled="inventoryDisable" />
            <span class="yuan">件</span>
          </el-form-item>
          <el-form-item label="库存预警：" prop="inventory_caution">
            <el-input v-model="ruleForm.inventory_caution" class="el-127" />
            <span class="yuan">件</span>
          </el-form-item>
          <!-- <el-form-item label="限购数量：" prop="quota">
            <el-input v-model="ruleForm.quota" class="el-127" />
            <span class="yuan">件</span>
          </el-form-item> -->
        </div>
        <el-form-item label="封面图：" prop="img_show">
          <el-upload
            :limit="1"
            action="https://wx.chengkenet.com/api/common/upload/"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :file-list="coverList"
          >
            <div slot="tip" class="el-upload__tip color-red">（建议尺寸：750px*750px）</div>
            <i class="el-icon-plus" />
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="imageUrl" alt>
          </el-dialog>
        </el-form-item>
        <el-form-item label="轮播图：" prop="commodity_img">
          <el-upload
            action="https://wx.chengkenet.com/api/common/upload/"
            list-type="picture-card"
            :on-preview="handleCarouselPictureCardPreview"
            :on-remove="handleCarouselRemove"
            :on-success="handleCarouselSuccess"
            :file-list="carouselList"
          >
            <div slot="tip" class="el-upload__tip color-red">（建议尺寸：750px*750px）</div>
            <i class="el-icon-plus" />
          </el-upload>
          <el-dialog :visible.sync="carouselDialogVisible">
            <img width="100%" :src="carouselImageUrl" alt>
          </el-dialog>
        </el-form-item>
        <!-- <el-form-item label="封面视频" prop="commodity_video">
          <el-upload
            class="upload-demo"
            :limit="1"
            action="https://wx.chengkenet.com/api/common/upload/"
            :on-success="handleVideoSuccess"
            :on-remove="handleVideoRemove"
            :file-list="videoList"
          >
            <el-button size="small">点击上传</el-button>
          </el-upload>
        </el-form-item> -->
        <el-form-item label="参数" class="textArea">
          <el-input
            v-model="params"
            type="textarea"
            placeholder="输完一行参数请按回车键换行,&nbsp; &nbsp;例： 型号：012345"
          />
        </el-form-item>
      </el-form>
    </div>
    <div class="bottom">
      <el-button style="margin-top: 12px;" @click="next('ruleForm')">下一步，选择属性价格</el-button>
    </div>
  </div>
</template>
<script>
const Err_OK = 200
import { addGoodsStepOne, editGoodsStepOne } from '@/api/goods'
import { mapGetters } from 'vuex'
const validate1 = (rule, value, callback) => {
  const pass = /^\d+(\.\d+)?$/.test(value)
  if (!pass) {
    callback(new Error('请输入有效数字'))
  } else {
    callback()
  }
}
const validate2 = (rule, value, callback) => {
  const pass = /^[0-9]\d*$/.test(value)
  if (!pass) {
    callback(new Error('请输入有效数字'))
  } else {
    callback()
  }
}
export default {
  props: {
    classificationList: {
      type: Array,
      default: () => []
    },
    brandList: {
      type: Array,
      default: () => []
    },
    stepOneDetail: {
      type: Object,
      default: () => {}
    }

  },
  data() {
    return {
      inventoryDisable: false,
      itemNo_disable: false,
      coverList: [],
      carouselList: [],
      videoList: [],
      disabled: true,
      noDisable: false,
      secClassicList: [],
      ruleForm: {
        name: '',
        item_no: '',
        kind: '',
        brand: '',
        cost: '',
        original_price: '',
        price: '',
        // discount_price: '',
        inventory: '',
        inventory_caution: '',
        // quota: '',
        commodity_img: [],
        img_show: '',
        commodity_video: '',
        parameter: []
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 30, message: '限30个字', trigger: 'blur' }
        ],
        kind: [{ required: true, message: '请选择分类', trigger: 'change' }],
        cost: [{ required: true, message: '请输入成本', trigger: 'blur', validator: validate1 }],
        original_price: [{ required: true, message: '请输入原价', trigger: 'blur', validator: validate1 }],
        price: [{ required: true, message: '请输入市场价', trigger: 'blur', validator: validate1 }],
        discount_price: [{ required: true, message: '请输入会员价', trigger: 'blur', validator: validate1 }],
        inventory: [{ required: true, trigger: 'blur', validator: validate2 }],
        inventory_caution: [{ required: true, trigger: 'blur', validator: validate2 }],
        // quota: [{ required: true, trigger: 'blur', validator: validate2 }],
        commodity_img: [{ required: true, message: '请上传轮播图', trigger: 'blur' }],
        img_show: [{ required: true, message: '请上传封面图', trigger: 'blur' }]
      },
      dialogVisible: false,
      carouselDialogVisible: false,
      value1: '',
      value2: '',
      value3: '',
      imageUrl: '',
      carouselImageUrl: '',
      params: '',
      readySend: false,
      isParamter: false

    }
  },
  computed: {
    ...mapGetters(['edit_type'])
  },
  watch: {
    stepOneDetail(newVal) {
      this.showGoodsInfo(newVal)
    }
  },
  mounted() {
    if (this.edit_type) {
      this.itemNo_disable = true
    }
  },
  methods: {
    // 返回上一步操作
    showGoodsInfo(newVal) {
      this.ruleForm.name = newVal.name
      this.ruleForm.item_no = newVal.item_no
      this.ruleForm.cost = newVal.cost
      this.ruleForm.original_price = newVal.original_price
      this.ruleForm.price = newVal.price
      // this.ruleForm.discount_price = newVal.discount_price
      this.ruleForm.inventory_caution = newVal.inventory_caution
      this.ruleForm.inventory = newVal.inventory
      // this.ruleForm.quota = newVal.quota
      this.ruleForm.commodity_img = newVal.commodity_img
      this.ruleForm.img_show = newVal.img_show
      if (newVal.commodity_video) {
        this.ruleForm.commodity_video = newVal.commodity_video
        this.videoList = [this.handleList(newVal.commodity_video)]
      }
      this.ruleForm.parameter = newVal.parameter
      this.findFirstClassicName(newVal.commodity_kind_id)
      this.findSecClassicName(newVal.commodity_kind_id)
      this.handleBrandChange(newVal.brand_id)
      this.setBrandName(newVal.brand_id)
      this.coverList = [this.handleList(newVal.img_show)]
      newVal.commodity_img.forEach((item) => {
        this.carouselList.push(this.handleList(item))
      })
      this.params = this.formatParameter(newVal.parameter)
      this.ruleForm.id = newVal.id
      this.readySend = true
      this.noDisable = true
      this.inventoryDisable = true
    },
    // 参数格式化
    formatParameter(data) {
      const _arr = data.map((item, index) => {
        return item.name + ':' + item.detail
      })
      return _arr.join('\n')
    },
    // 图片、视频格式化
    handleList(url) {
      const oIndex = url.lastIndexOf('/')
      const name = url.slice(oIndex + 1)
      return { name, url }
    },
    // 一级分类格式化
    findFirstClassicName(id) {
      // 先从一级里面找
      const firstClassicId = this.classificationList.findIndex((item, index) => {
        return item.id === id
      })
      if (firstClassicId >= 0) {
        this.value1 = this.classificationList[firstClassicId].kind_name
        return
      }
      const indexObj = this.findClassicIndex(id)
      if (indexObj.oIndex >= 0) {
        this.value1 = this.classificationList[indexObj.oIndex].kind_name
      } else {
        this.value1 = ''
      }
    },
    // 二级分类格式化
    findSecClassicName(id) {
      const indexObj = this.findClassicIndex(id)
      console.log(this.classificationList)
      if (indexObj.oIndex >= 0) {
        this.value2 = this.classificationList[indexObj.oIndex].lower[indexObj.fIndex].kind_name
      } else {
        this.value2 = ''
      }

      this.ruleForm.kind = id
    },
    findClassicIndex(secId) {
      // 根据二级找一级
      let oIndex
      let fIndex
      for (let i = 0; i <= this.classificationList.length - 1; i++) {
        fIndex = this.classificationList[i].lower.findIndex((secItem, secIndex) => {
          return secItem.id === secId
        })
        if (fIndex >= 0) {
          oIndex = i
          break
        }
      }
      return { oIndex, fIndex }
    },
    handleChange(id) {
      // 根据一级id找二级
      const fIndex = this.classificationList.findIndex((item, index) => {
        return item.id === id
      })
      if (fIndex >= 0) {
        this.secClassicList = this.classificationList[fIndex].lower
        this.disabled = false
      }
    },
    // 选择二级分类
    handleSecClassicChange(id) {
      this.ruleForm.kind = id
    },
    // 选择品牌
    handleBrandChange(id) {
      this.ruleForm.brand = id
    },
    setBrandName(id) {
      const fIndex = this.brandList.findIndex((item, index) => {
        return item.id === id
      })
      if (fIndex >= 0) {
        this.value3 = this.brandList[fIndex].id
      }
    },
    // 展示图片
    handlePictureCardPreview(file) {
      this.imageUrl = file.url
      this.dialogVisible = true
    },
    // 删除图片
    handleRemove(file, fileList) {
      this.ruleForm.img_show = ''
    },
    // 封面图上传成功
    handleSuccess(response) {
      if (response.code === Err_OK) {
        this.ruleForm.img_show = response.data.file
      }
    },
    // 展示轮播图
    handleCarouselPictureCardPreview(file) {
      this.carouselImageUrl = file.url
      this.carouselDialogVisible = true
    },
    // 删除轮播图
    handleCarouselRemove(file, fileList) {
      const fIndex = this.ruleForm.commodity_img.findIndex((item, index) => {
        return item === file.response.data.file
      })
      if (fIndex >= 0) {
        this.ruleForm.commodity_img.splice(fIndex, 1)
      }
    },
    // 轮播图上传成功
    handleCarouselSuccess(response) {
      if (response.code === Err_OK) {
        this.ruleForm.commodity_img.push(response.data.file)
      }
    },
    // 视频上传成功
    handleVideoSuccess(response) {
      if (response.code === Err_OK) {
        const isAudio = /^https?.+\.(swf|avi|flv|mpg|rm|mov|wav|asf|3gp|mkv|rmvb)$/i.test(response.data.file)
        if (!isAudio) {
          this.$message({
            showClose: true,
            type: 'warning',
            message: '格式不正确，请上传视频！'
          })
          return
        }
        this.ruleForm.commodity_video = response.data.file
        this.readySend = true
      }
    },
    // 删除视频
    handleVideoRemove() {
      this.ruleForm.commodity_video = ''
    },
    // 下一步
    next(formName) {
      this._formatParams(this.params)
      this.$refs[formName].validate((valid) => {
        if (valid && this.isParamter) {
          if (!this.ruleForm.commodity_video) {
            this.readySend = true
          }
          // 判断视频是否上传成功
          if (!this.readySend) {
            this._toastError('视频上传中...')
            return
          }
          // 上传操作
          if (!this.ruleForm.id) {
            this._addGoodsStepOne(this.ruleForm)
              .then(res => {
                this.$emit('next', res.data.id)
                window.scrollTo(0, 0)
              })
              .catch(err => {
                console.log(err)
              })
          } else {
            // 修改操作
            this._editGoodsStepOne(this.ruleForm)
              .then(res => {
                this.$emit('next', res.data.id)
                window.scrollTo(0, 0)
              })
              .catch(err => {
                console.log(err)
              })
          }
        } else {
          return false
        }
      })
    },
    // 上传参数格式化
    _formatParams(params) {
      if (!params) {
        this.isParamter = true
        return
      }
      const temp1 = params.split(/\n/)
      this.ruleForm.parameter = []
      for (let i = 0; i <= temp1.length - 1; i++) {
        const temp2 = temp1[i].split(/\:|\：/)
        if (temp2.length <= 1) {
          this.$message({
            message: '参数格式不正确',
            type: 'warning',
            showClose: true
          })
          this.isParamter = false
          break
        } else {
          this.isParamter = true
          this.ruleForm.parameter.push({ name: temp2[0].trim(), detail: temp2[1].trim() })
        }
      }
      // this.ruleForm.parameter = JSON.stringify(this.ruleForm.parameter)
    },
    // 上传第一步接口
    _addGoodsStepOne(params) {
      return new Promise((resolve, reject) => {
        addGoodsStepOne(params)
          .then(res => {
            if (res.code === Err_OK) {
              this._toast(res.message)
              resolve(res)
            }
          })
          .catch(err => {
            console.log(err)
            reject()
          })
      })
    },
    // 修改第一步接口
    _editGoodsStepOne(params) {
      return new Promise((resolve, reject) => {
        editGoodsStepOne(params)
          .then(res => {
            if (res.code === Err_OK) {
              this._toast(res.message)
              resolve(res)
            }
          })
          .catch(err => {
            console.log(err)
            reject()
          })
      })
    },
    // 显示成功toast
    _toast(message) {
      this.$message({
        message: message,
        type: 'success'
      })
    },
    // 显示失败信息
    _toastError(message) {
      this.$message({
        message: message,
        type: 'warning'
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.classify,
.price-wrapper,
.stock {
  display: flex;
  align-content: center;
  justify-content: flex-start;
}
.content {
  border-bottom: 1px solid #eee;
}
.bottom {
  .el-button {
    display: block;
    width: 200px;
    height: 48px;
    margin: 0 auto;
    border-radius: 6px;
    background-color: rgba(64, 158, 255, 1);
    text-align: center;
    color: #ffff;
    margin-bottom: 50px;
  }
}
.yuan {
  position: absolute;
  top: 0;
  right: 7px;
  color: #101010 !important;
}
.el-input {
  width: auto;
}
.el-input /deep/ .el-input__inner {
  width: 414px;
  height: 36px;
  border-radius: 3px;
  border: 1px solid rgba(226, 229, 234, 1);
}
.el-form-item /deep/ .el-form-item__content {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  span {
    background-color: rgba(255, 0, 0, 0);
    color: rgba(189, 189, 189, 1);
    font-size: 12px;
    font-family: Roboto;
  }
}
.el-form-item /deep/ .el-icon-zoom-in {
  font-size: 26px;
  color: #fff;
}
.el-form-item /deep/ .el-icon-delete {
  font-size: 26px;
  color: #fff;
}
.el-progress /deep/ .el-progress-bar__outer {
  height: 4px !important;
}
.el-progress {
  margin-top: -5px;
}
.el-200 {
  &.el-input /deep/ .el-input__inner {
    width: 200px !important;
  }
}
.upload-demo /deep/ .el-upload-list__item {
  margin: 0;
}
.el-127 {
  &.el-input /deep/ .el-input__inner {
    width: 127px !important;
  }
}
.ml-10 {
  margin-left: 10px;
}
.color-red {
  color: red;
}
.textArea {
  &.el-form-item /deep/ textarea {
    width: 414px;
    height: 154px;
    line-height: 20px;
    border-radius: 3px;
    border: 1px solid rgba(226, 229, 234, 1);
  }
}
</style>
